package com.supcon.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.supcon.entity.User;
import com.supcon.service.UserService;
import com.supcon.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author BeautifulHao
 * @description 用户
 * @create 2019-04-25 14:07
 **/
@RequestMapping("/api/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 详情
     */
    @GetMapping("/info")
    public ResultInfo<User> info(User user) {
        User info = userService.getOne(Condition.getQueryWrapper(user));
        if(info !=null) {
            return new ResultInfo<>(true, info, "get success!");
        }
        else {
            return new ResultInfo<>(false,null,"nothing get!");
        }
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    public ResultInfo<Object> remove(@RequestParam String ids){

        List<Integer> arrayList = Arrays.stream(ids.split(","))
                .filter(item->item !=null && item !="")
                .map(Integer::valueOf).collect(Collectors.toList());

        return new ResultInfo<>(userService.removeByIds(arrayList),null,"remove success");
    }

    /**
     * 新增或修改
     */
    @PostMapping("/submit")
    public ResultInfo<Map<String,Object>> submit(@Valid @RequestBody User user, BindingResult bindingResult) {

        ResultInfo<Map<String,Object>> resultInfo = new ResultInfo<>(false,new HashMap<>(),"");

        if (bindingResult.hasErrors()) {
            resultInfo.setMessage(bindingResult.getFieldError().getDefaultMessage());
            for (FieldError error : bindingResult.getFieldErrors()) {
                resultInfo.getResults().put(error.getField(),error.getDefaultMessage());
            }
        } else {
            boolean saveOrUpdate = userService.saveOrUpdate(user);
            resultInfo.setSuccess(saveOrUpdate);
            resultInfo.getResults().put("info",user);
        }

        return resultInfo;
    }

    /**
    * 批量新增
    */
    @PostMapping("/batchAdd")
    public ResultInfo<Boolean> batchAdd(@Valid @RequestBody List<User> users){
        boolean saveBatch = userService.saveBatch(users);
        return new ResultInfo<>(saveBatch, saveBatch, null);
    }

    /**
     * 用户列表
     */
    @GetMapping("/list")
    public PageResultInfo<List<User>> list(@RequestParam Map<String, Object> user, Query query) {
        QueryWrapper<User> queryWrapper = handQueryCondition(user);
        IPage<User> pages = userService.page(Condition.getPage(query),queryWrapper);
        Pagination pagination = new Pagination();
        pagination.setCurrentPage(pages.getCurrent());
        pagination.setTotal(pages.getTotal());
        pagination.setPageSize(pages.getSize());

        PageResultInfo<List<User>> resultInfo = new PageResultInfo<>();
        resultInfo.setSuccess(true);
        resultInfo.setPagination(pagination);
        resultInfo.setResults(pages.getRecords());
        resultInfo.setMessage("ok");
        return resultInfo;
    }

    @GetMapping("/dic")
    public ResultInfo<Map<String,List<KeyAndValue>>> dic(){
        Map<String,List<KeyAndValue>> dic = new HashMap<>();

        List<KeyAndValue> gender = new ArrayList<>();
        gender.add(new KeyAndValue(0,"男性"));
        gender.add(new KeyAndValue(1,"女性"));
        gender.add(new KeyAndValue(2,"未知"));

        dic.put("gender",gender);

        ArrayList<KeyAndValue> status = new ArrayList<>();
        status.add(new KeyAndValue(0,"离职"));
        status.add(new KeyAndValue(1,"在职"));

        dic.put("status",status);

        ResultInfo resultInfo = new ResultInfo(true, dic, "");

        return resultInfo;
    }

    private QueryWrapper<User> handQueryCondition(Map<String, Object> user){
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.setEntity(BeanUtils.instantiateClass(User.class));

        if(user.containsKey("code")){
            qw.like("code",user.get("code"));
        }

        if(user.containsKey("name")){
            qw.like("name",user.get("name"));
        }

        if(user.containsKey("cardNo")){
            qw.like("card_no",user.get("cardNo"));
        }

        if(user.containsKey("phone")){
            qw.like("phone",user.get("phone"));
        }

        if(user.containsKey("email")){
            qw.like("email",user.get("email"));
        }

        if(user.containsKey("statusString")){
            String[] statuses = user.get("statusString").toString().split(",");
            qw.in("status",statuses);
        }
        if(user.containsKey("genderString")){
            String[] genders = user.get("genderString").toString().split(",");
            qw.in("gender",genders);
        }

        if(user.containsKey("birthday_from")){
            Object birthday = user.get("birthday_from");
            qw.ge("birthday",birthday);
        }

        if(user.containsKey("birthday_to")){
            Object birthday = user.get("birthday_to");
            qw.le("birthday",birthday);
        }

        return qw;
    }

    /**
     * 异常测试
     */
    @GetMapping("/error")
    public String error(){
        throw new FriendlyException("异常测试");
    }
}
